#include "roster.h"

#include "rostermodel.h"
#include "rosterelements.h"
#include "collections/unitcollection.h"

#include <QDebug>

Roster::Roster(ColumnHeader *header) : points(0.0)
{
    parentItem = new RosterElement(NULL);
    rosterModel = new RosterModel(parentItem, header);
}

Roster::~Roster() {
    delete rosterModel;
    delete parentItem;
}

RosterModel* Roster::model() {
    return rosterModel;
}

void Roster::addRosterElement(RosterElement *element, RosterElement *parent) {
    Q_ASSERT(element);

    if(parent) {
        rosterModel->beginInsertRows(rosterModel->index(parent, 0), parent->childCount(), parent->childCount());
        parent->addChild(element);
    } else {
        rosterModel->beginInsertRows(QModelIndex(), parentItem->childCount(), parentItem->childCount());
        parentItem->addChild(element);
    }

    rosterModel->endInsertRows();
}

void Roster::removeRosterElement(int row) {
    RosterElement *e = parentItem->child(row);
    if(e) {
        rosterModel->beginRemoveRows(QModelIndex(), row, row);
        delete e;
        rosterModel->endRemoveRows();
    }
}

void Roster::clearAll() {
    // \TODO: Implement Roster::clearAll()
}

void Roster::addError(const QString& error) {
    errors.insert(error);
    emit validationChanged(errors);
}

void Roster::removeError(const QString& error) {
    if(errors.remove(error))
        emit validationChanged(errors);
}

QSet<QString> Roster::getValidationErrors() const {
    return errors;
}

int Roster::count() {
    return parentItem->childCount();
}

RosterElement* Roster::at(int i) {
    return static_cast<RosterElement*>(parentItem->children.at(i));
}

RosterElement* Roster::value(int i) {
    return static_cast<RosterElement*>(parentItem->children.value(i, NULL));
}

void Roster::amountPoints(float points) {
    if(points != 0.0) {
        this->points += points;
        emit pointsChanged(this->points);
    }
}

void Roster::forceUpdate(RosterElement *element) {
    rosterModel->emitDataChanged(element);
}

void Roster::aboutToRemoveChildren(RosterElement *parent, int first, int end) {
    rosterModel->beginRemoveRows(rosterModel->index(parent,0),first,end);
}

void Roster::childrenRemoved() {
    rosterModel->endRemoveRows();
}

void Roster::aboutToAddChild(RosterElement *parent) {
    int row = parent->childCount();
    rosterModel->beginInsertRows(rosterModel->index(parent,0), row, row);
}

void Roster::childAdded() {
    rosterModel->endInsertRows();
}
